package controller

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"go-barrage/dto"
	"go-barrage/models"
	"go-barrage/response"
	"go-barrage/utils"
	"go-barrage/vo"
	"log"
	"time"
)

func Login(c *gin.Context) {
	var systemUserDTO dto.SystemUserDto
	err := c.Bind(&systemUserDTO)
	if err != nil {
		log.Panicln(err)
	}
	email := systemUserDTO.Email
	password := systemUserDTO.Password
	log.Println("登录请求信息为:", systemUserDTO)
	if email == "" || password == "" {
		response.ParamError(c)
		return
	}

	userInfo := models.GetUserInfoByEmail(&email)
	if userInfo.Id == 0 {
		response.DataNotExist(c, "用户数据不存在")
		return
	}

	checkResult := utils.CheckPasswordHash(userInfo.Password, password)
	if !checkResult {
		response.PasswordError(c)
		return
	}

	signingKey := utils.RandStr(22)
	token := utils.CreateToken(signingKey)

	cacheUserInfo := vo.SystemUserVo{
		Id:         userInfo.Id,
		Token:      token,
		SigningKey: signingKey,
	}

	jsonToken, _ := json.Marshal(cacheUserInfo)

	utils.SetExp(token, string(jsonToken), time.Hour*24)

	response.Success(c, token)

}

func Register(c *gin.Context) {
	//var systemUserDTO dto.SystemUserDto
	//err := c.Bind(&systemUserDTO)
	//if err != nil {
	//	panic(err)
	//}
	//email := systemUserDTO.Email
	//password := systemUserDTO.Password
	//log.Println("登录请求信息为:", systemUserDTO)
	//if email == "" || password == "" {
	//	response.ParamError(c)
	//	return
	//}
	//
	//if models.CheckUserIsExist(email) {
	//	response.DataExist(c, "该用户已经存在")
	//	return
	//}
	//
	//signingKey := utils.RandSigningKey(22)
	//log.Println("用户:", email, "不存在可以注册为：", email)

	response.ModuleClose(c)

}
